import router from "./router";
import store from "@/store";
import {queryOrderStatus} from "@/api/index"
import vm from "@/main";

router.beforeEach((to, from, next) => {

  /* 未登录 */
  if (!store.getters["user/Yhdtoken"]) {
    if (to.matched.some(record => record.meta.requiresAuth)) {
      next({
        path: "/login",
        query: { redirect: to.fullPath }
      });
    } else {
      next(); // 确保一定要调用 next()
    }
  } else {
    /* 已登录 */
    if (to.path === "/login") {
      if (to.query && to.query.redirect) {
        next({
          path: to.query.redirect
        });
      } else {
        next({ path: "/" });
      }
    } else {
      if (to.meta.roles) {
        /* 通过meta.roles判断是否与当前用户权限匹配 */
        if (to.meta.roles.includes(store.getters["user/role"])) {
          // 首页点击申请进入申请页之前判断，已有订单则跳转我的申请
          if(to.path == "/apply1") {
            queryOrderStatus({
              userId: store.getters["user/userId"]
            }).then( res => {
              if(res.respCode !== "000000") {
                window.sessionStorage.setItem("orderId", res.params.propertyNumber);
                console.log(res)
                /* 有一个申请未完成审批 */
                vm.$messagebox({
                  title: "温馨提示",
                  message: res.respMsg,
                  showConfirmButton: true,
                  showCancelButton: true,
                  confirmButtonText: "查看",
                  cancelButtonText: "取消"
                }).then(res => {
                  if (res === "confirm") {
                    next({ path: "/tab/2" });
                  }else{
                    next({path: "/"});
                  }
                });
              }
            })
          };
          next();
        } else {
          next({ path: "/401" });
        }
      } else {
        next();
      }
    }
  }
});

router.afterEach((to, from) => {
  // to and from are both route objects.
  document.title = to.meta.title;
});
